import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { PrismaService } from 'src/prisma/prisma.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(
    configService: ConfigService,
    private prisma: PrismaService,
  ) {
    super({
      //解析用户提交的Bearer Token header数据
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      //加密码的secret
      secretOrKey: configService.get('TOKEN_SECRET'),
    });
  }

  //验证通过后结果用户资料
  //自动把user注入到Request中

  async validate({ sub: id }) {
    return this.prisma.user.findUnique({
      where: { id },
      select: {
        username: true,
        avatar: true,
        roles: true,
        id: true,
      },
    });
  }
}
